<template>
  <div>
    <FormModal :columns="items" :model="model" ref="formModalRef"> </FormModal>
    <!-- 参数保存弹窗 -->
    <SseModal />
  </div>
</template>

<script setup lang="tsx">
import { computed, ref } from 'vue';
import { useFormModal } from '@boeyo/hooks';
import { useDicts } from '@boeyo/portal';
import { BoFormProps } from '@boeyo/ui';
import { message } from 'ant-design-vue';
import { Rule } from 'ant-design-vue/es/form';
import Encoding from 'encoding-japanese';
import { useSseModal } from '@/hooks/useSseModal';
import { getTriggerInfo } from '../api';

const model = ref<any>({});
const props = defineProps<{
  tableRef: any;
  stationId: string;
}>();

const emit = defineEmits(['update:value']);

const dictArr = [
  'server_work_mode',
  'ntp_time_interval',
  'lowfreq_type',
  'highfreq_type',
  'filter_type',
  'trigger_type',
  'install_method',
  'output_times',
];
const {
  ntpTimeIntervalOptions,
  filterTypeOptions,
  triggerTypeOptions,
  serverWorkModeOptions,
  installMethodOptions,
  outputTimesOptions,
} = useDicts(dictArr);

const format = (options) => {
  return options.map((item) => {
    item.value = +item.value;
    return item;
  }) as any;
};

const { FormModal, open } = useFormModal({
  size: 'large',
  column: 3,
  formProps: {
    labelCol: {
      style: {
        width: '250px',
      },
    },
    wrapperCol: {
      style: {
        width: '100%',
      },
    },
  },
  afterClose: () => {
    emit('update:value', false);
  },
});

const { SseModal, open: openSse } = useSseModal();

const buildParams = (data) => {
  const content = `
          #network parameter
          IPADDR=${model.value.ip};    							//IP地址
          NETMASK=${model.value.netmask};    							//子网掩码
          GATEWAY=${model.value.gateway};    							//网关
          PORT=${model.value.port};    							//数据服务端口
          MAIN_NTP=${model.value.mainsntpip};    							//主SNTP服务器IP地址
          BAK_NTP=${model.value.baksntpip};    							//备SNTP服务器IP地址
          NTP_INTERVAL=${model.value.sntpinterval};    // NTP授时间隔 0:30秒,1:5分钟,2:20分钟
          NTP_DELAY=${model.value.sntpdelay};    							//SNTP网络延迟控制
          AUTO_SEND=ON;    							//主动传送ON/OFF
          SERVER1_IP=${model.value.serverip1};    							//服务器1IP地址
          SERVER1_PORT=${model.value.serverport1};    							//服务器1端口
          SERVER2_IP=${model.value.serverip2};    							//服务器2IP地址
          SERVER2_PORT=${model.value.serverport2};    							//服务器2IP地址
          SERVER3_IP=${model.value.serverip3};    							    //服务器3IP地址
          SERVER3_PORT=${model.value.serverport3};    							//服务器3IP地址
          SERVER4_IP=${model.value.serverip4};    							    //服务器4IP地址
          SERVER4_PORT=${model.value.serverport4};    							//服务器4IP地址
          #trigger parameter
          LOW_FREQ=${model.value.lowfreq};    //低频截止频率（Hz）0:0.1Hz,1:0.3Hz,2:0.5Hz,3:1.0Hz
          HIGH_FREQ=${model.value.highfreq};    //高频截止频率（Hz）0:10Hz,1:20Hz,2:40Hz
          TRIG_TYPE=${model.value.trigtype};    //触发类型0:无,1:电平触发,2:STA/LTA触发
          TRIG_VALUE=${model.value.trigvalue};    //电平触发阈值Gal
          END_VALUE=${model.value.endvalue};    //电平结束阈值Gal
          MAX_TIME=${model.value.maxtime};    //最大触发控制时间
          END_COUNT=${model.value.endcount};    //结束判别次数
          PRE_TIME=${model.value.pretime};      //事件前记录时间秒
          POST_TIME=${model.value.posttime};    //事件后记录时间秒
          VOTE_NUM=${model.value.nvote};    //触发总票数
          B_TH=${model.value.b_th};    // STA/LTA触发模式时触发阈值
          E_TH=${model.value.e_th};    // STA/LTA触发模式时结束阈值
          LTA_T=${model.value.lta_t};    //STA时间窗
          STA_T=${model.value.sta_t};     //LTA时间窗
          #properity parameter
          SITE_NAME=${model.value.sitename};    //台站名称
          NET_NAME=${model.value.netname};      //台网名称
          SITE_TYPE=${model.value.sitetype};    //场地类型，任意输入文字
          POS_LABEL=${model.value.poslabel};    	 //位置标识
          CHN_LABEL=${model.value.chnlabel};    	//通道标识
          LAT=${model.value.lat};    //纬度
          LON=${model.value.lon};    //经度
          ALT=${model.value.height};    			//高程
          #work parameter    		//以下为工作参数设置项
          SAMPLE_RATE=${model.value.samplerate};    	//采样率	50,100,200
          OUTPUT_PERIOD=${model.value.outputt};    //输出数据包时间间隔0:1s,1:0.5s,2:0.2s
          ASM_WAY=${model.value.asmway};    //安装方式0:水平,1:壁挂
          ASM_DIR=${model.value.asmdir};    //安装方位角
          FILTER_TYPE=${model.value.filtertype};    //滤波器类型 0:线性相位,1:最小相位
          #server1 parameter    	//服务器用户1设置
          SERVER1_MODE=${model.value.server1mode};    //初始模式0:连续,1:触发传输波形,2:触发不传波形,3:触发连续波形
          SERVER1_PSW=${model.value.server1psw};    //服务器1密码
          #server2 parameter    	//服务器用户2设置
          SERVER2_MODE=${model.value.server2mode};    //初始模式0:连续,1:触发传输波形,2:触发不传波形,3:触发连续波形
          SERVER2_PSW=${model.value.server2psw};  	//服务器2密码
          #user parameter    	//管理用户设置
          ADMIN_USER_NAME=${model.value.admin_username};    	//用户名
          ADMIN_PASSWORD=${model.value.admin_password};       //用户密码
          `;
  // 将数据转为GBK格式
  const gbkContent = Encoding.convert(content, 'GBK', 'UNICODE');
  const blob1 = new Blob([gbkContent]);
  const cfg = new File([blob1], 'common.cfg');
  const formData = new FormData();

  const form = JSON.parse(JSON.stringify(model.value));
  const json = JSON.stringify(form);

  formData.append('file', cfg);
  formData.append('deviceCode', model.value.deviceCode);
  formData.append('data', json);
  formData.append('fileType', '0');
  formData.append('stationId', props.stationId);
  formData.append('updateType', '0');
  return formData;
};

//实现自定义异步函数
function createPromise() {
  let resolve, reject;
  const promise = new Promise((res, rej) => {
    resolve = res;
    reject = rej;
  });
  return { promise, resolve, reject };
}

// 获取触发器信息
const getTriggerData = async () => {
  const res: any = await getTriggerInfo(props.stationId);
  model.value = res.data;
  // 格式化数据
  model.value.lon = (+model.value.lon || 0).toFixed(4); //经度
  model.value.lat = (+model.value.lat || 0).toFixed(4); //纬度
  model.value.sta_t = model.value.sta_t / 100; //STA时间窗
  model.value.lta_t = model.value.lta_t / 100; // LTA时间窗
  model.value.e_th = model.value.e_th / 10; // STA/LTA触发模式时结束阈值
  model.value.b_th = model.value.b_th / 10; // STA/LTA触发模式时触发阈值
  model.value.trigvalue = model.value.trigvalue / 10; //电平触发阈值Gal
  model.value.endvalue = model.value.endvalue / 10; //电平结束阈值Gal
  model.value.asmdir = model.value.asmdir / 10; //安装方位角
  if (!isNaN(model.value.sntpdelay))
    model.value.sntpdelay = parseFloat(model.value.sntpdelay) / 1000; //SNTP网络延迟控制

  open({
    title: '查看详情',
    request: async (params: any) => {
      const { resolve, promise } = createPromise();

      // 重构参数以文件形式传参
      const saveParams = buildParams(model.value);
      // SSE方式保存数据
      openSse({
        title: '保存参数',

        url: '/api/device/updateParam',
        data: saveParams,
        method: 'post',
        onClose() {
          resolve(1);
        },
      });
      await promise;
      emit('update:value', false);
      message.success('操作成功，请重启设备');
      props.tableRef?.refresh();
    },
  });
};
getTriggerData();

// 校验规则
const chnLabelValid = async (_rule: Rule, value: string) => {
  if (!/^[A-Z]{2}$/.test(value)) {
    return Promise.reject('应该为2位大写字母');
  } else Promise.resolve();
};

const trigValid = async (_rule: Rule, value: number) => {
  if (!value) return Promise.reject('请输入触发阈值');
  else if (value < model.value.endValue)
    return Promise.reject('应大于结束阈值');
  else if (value < 0) return Promise.reject('不能为负数');
  else return integerValid(_rule, value);
};
const endValid = async (_rule: Rule, value: number) => {
  if (!value) return Promise.reject('请输入结束阈值');
  else if (value > model.value.trigValue)
    return Promise.reject('应小于触发阈值');
  else if (value < 0) return Promise.reject('不能为负数');
  else return integerValid(_rule, value);
};
const thValid = async (_rule: Rule, value: number) => {
  if (model.value.bth < model.value.eth)
    return Promise.reject('触发比值应大于结束比值');
  else return integerValid(_rule, value);
};
const ntpDelayValid = async (_rule: Rule, value: string) => {
  if (parseInt(value) > 500 || parseInt(value) < 100)
    return Promise.reject('范围在200~500之内');
  else Promise.resolve();
};

const integerValid = async (_rule: Rule, value: number) => {
  if (/\./.test(value + '')) return Promise.reject('不能包含小数点');
  else Promise.resolve();
};
const ipValid = async (_rule: Rule, value: string) => {
  if (
    !/^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$/.test(
      value,
    )
  )
    return Promise.reject('请输入正确的IP地址');
  else Promise.resolve();
};
const portValid = async (_rule: Rule, value: number) => {
  if (isNaN(value)) return Promise.reject('请填入数字');
  else if (value < 0 || value > 65535)
    return Promise.reject('端口范围在0~65535之间');
  else return integerValid(_rule, value);
};

const items = computed<BoFormProps['columns']>(() => [
  {
    title: '',
    dataIndex: 'baseInfo',
    valueType: 'input',
    colProps: { span: 24 },
    formItemRender(state) {
      return <div class='module-title'>属性参数</div>;
    },
  },
  {
    title: '台网名称',
    dataIndex: 'netname',
    valueType: 'input',
  },
  {
    title: '台站名称',
    dataIndex: 'sitename',
    valueType: 'input',
  },
  {
    title: '设备序列号',
    dataIndex: 'deviceCode',
    valueType: 'input',
    disabled: true,
  },
  {
    title: '经度',
    dataIndex: 'lon',
    valueType: 'input',
  },
  {
    title: '纬度',
    dataIndex: 'lat',
    valueType: 'input',
  },
  {
    title: '场地类型',
    dataIndex: 'sitetype',
    valueType: 'input',
    fieldProps: {
      placeholder: '请输入场地类型',
      // options: siteTypeOptions.value as any,
    },
  },
  {
    title: '高程',
    dataIndex: 'height',
    valueType: 'input',
  },
  {
    title: '位置代码',
    dataIndex: 'poslabel',
    valueType: 'input',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请输入位置代码',
          trigger: 'blur',
        },
      ],
    },
  },
  {
    title: '通道代码',
    dataIndex: 'chnlabel',
    valueType: 'input',
    formItemProps: {
      rules: [
        {
          required: true,
          validator: chnLabelValid,
          trigger: 'blur',
        },
      ],
    },
  },
  {
    title: '',
    dataIndex: 'workInfo',
    valueType: 'input',
    colProps: { span: 24 },
    formItemRender(state) {
      return <div class='module-title'>工作参数</div>;
    },
  },
  {
    title: '采样率',
    dataIndex: 'samplerate',
    valueType: 'input',
  },
  {
    title: '数据打包间隔时间',
    dataIndex: 'outputt',
    valueType: 'select',
    fieldProps: {
      placeholder: '请选择数据打包间隔时间',
      options: format(outputTimesOptions.value) as any,
    },
  },
  {
    title: '安装方式',
    dataIndex: 'asmway',
    valueType: 'radio',
    fieldProps: {
      placeholder: '请选择安装方式',
      options: format(installMethodOptions.value) as any,
    },
  },
  {
    title: '安装方位',
    dataIndex: 'asmdir',
    valueType: 'input',
    colProps: { span: 16 },
    fieldProps: {
      placeholder: '请输入安装方位',
      addonAfter: '°与真北重合',
      addonBefore: '仪器指北逆时针旋转',
    },
  },
  {
    title: '',
    dataIndex: 'triggerInfo',
    valueType: 'input',
    colProps: { span: 24 },
    formItemRender(state) {
      return <div class='module-title'>触发参数</div>;
    },
  },
  {
    title: '触发方式',
    dataIndex: 'trigtype',
    valueType: 'select',
    fieldProps: {
      placeholder: '请选择触发方式',
      options: format(triggerTypeOptions.value) as any,
    },
  },
  {
    title: '滤波器类型',
    dataIndex: 'filtertype',
    valueType: 'select',
    fieldProps: {
      placeholder: '请选择滤波器类型',
      options: format(filterTypeOptions.value) as any,
    },
  },
  {
    title: '触发阈值(gal)',
    dataIndex: 'trigvalue',
    valueType: 'input',
    formItemProps: {
      rules: [
        {
          required: true,
          validator: trigValid,
          trigger: 'blur',
        },
      ],
    },
    hidden: (state) => [0, 2].includes(state.trigtype),
  },
  {
    title: '结束阈值(gal)',
    dataIndex: 'endvalue',
    valueType: 'input',
    formItemProps: {
      rules: [
        {
          required: true,
          validator: endValid,
          trigger: 'blur',
        },
      ],
    },
    hidden: (state) => [0, 2].includes(state.trigtype),
  },
  {
    title: '结束判别次数',
    dataIndex: 'endcount',
    valueType: 'input',
    hidden: (state) => [0, 2].includes(state.trigtype),
  },
  {
    title: '最大触发时间控制',
    dataIndex: 'maxtime',
    valueType: 'input',
  },
  {
    title: '事件前记录时间',
    dataIndex: 'pretime',
    valueType: 'input',
  },
  {
    title: '事件后记录时间',
    dataIndex: 'posttime',
    valueType: 'input',
  },
  {
    title: '触发比值',
    dataIndex: 'b_th',
    valueType: 'input',
    formItemProps: {
      rules: [
        {
          // required: true,
          validator: thValid,
          trigger: 'blur',
        },
      ],
    },
    hidden: (state) => [0, 1].includes(state.trigtype),
  },
  {
    title: '结束比值',
    dataIndex: 'e_th',
    valueType: 'input',
    formItemProps: {
      rules: [
        {
          // required: true,
          validator: thValid,
          trigger: 'blur',
        },
      ],
    },
    hidden: (state) => [0, 1].includes(state.trigtype),
  },
  {
    title: 'STA时间窗(秒)',
    dataIndex: 'sta_t',
    valueType: 'input',
    hidden: (state) => [0, 1].includes(state.trigtype),
  },
  {
    title: 'LTA时间窗(秒)',
    dataIndex: 'lta_t',
    valueType: 'input',
    hidden: (state) => [0, 1].includes(state.trigtype),
  },
  {
    title: '触发总票数',
    dataIndex: 'nvote',
    valueType: 'input',
  },
  {
    title: '',
    dataIndex: 'netInfo',
    valueType: 'input',
    colProps: { span: 24 },
    formItemRender(state) {
      return <div class='module-title'>网络参数</div>;
    },
  },
  {
    title: 'IP',
    dataIndex: 'ip',
    valueType: 'input',
    formItemProps: {
      rules: [
        {
          required: true,
          validator: ipValid,
          trigger: 'blur',
        },
      ],
    },
  },
  {
    title: '子网掩码',
    dataIndex: 'netmask',
    valueType: 'input',
  },
  {
    title: '网关',
    dataIndex: 'gateway',
    valueType: 'input',
  },
  {
    title: '数据服务端口',
    dataIndex: 'port',
    valueType: 'input',
    formItemProps: {
      rules: [
        {
          required: true,
          validator: portValid,
          trigger: 'blur',
        },
      ],
    },
  },
  {
    title: '主NTP服务器',
    dataIndex: 'mainsntpip',
    valueType: 'input',
    formItemProps: {
      rules: [
        {
          required: true,
          validator: ipValid,
          trigger: 'blur',
        },
      ],
    },
  },
  {
    title: '备NTP服务器',
    dataIndex: 'baksntpip',
    valueType: 'input',
    formItemProps: {
      rules: [
        {
          required: true,
          validator: ipValid,
          trigger: 'blur',
        },
      ],
    },
  },
  {
    title: 'NTP延迟控制',
    dataIndex: 'sntpdelay',
    valueType: 'input',
    formItemProps: {
      rules: [
        {
          required: true,
          validator: ntpDelayValid,
          trigger: 'blur',
        },
      ],
    },
  },
  {
    title: 'NTP授时间隔',
    dataIndex: 'sntpinterval',
    valueType: 'select',
    fieldProps: {
      placeholder: '请选择NTP授时间隔',
      options: format(ntpTimeIntervalOptions.value) as any,
    },
  },
  {
    title: '管理服务器地址(IP4)',
    dataIndex: 'serverip4',
    valueType: 'input',
    formItemProps: {
      rules: [
        {
          required: true,
          validator: ipValid,
          trigger: 'blur',
        },
      ],
    },
  },
  {
    title: '管理服务器端口号(PORT4)',
    dataIndex: 'serverport4',
    valueType: 'input',
    formItemProps: {
      rules: [
        {
          required: true,
          validator: portValid,
          trigger: 'blur',
        },
      ],
    },
  },
  {
    title: '数据服务器1IP',
    dataIndex: 'serverip1',
    valueType: 'input',
    formItemProps: {
      rules: [
        {
          required: true,
          validator: ipValid,
          trigger: 'blur',
        },
      ],
    },
  },
  {
    title: '数据服务器1端口号',
    dataIndex: 'serverport1',
    valueType: 'input',
    formItemProps: {
      rules: [
        {
          required: true,
          validator: portValid,
          trigger: 'blur',
        },
      ],
    },
  },
  {
    title: '数据服务器1工作模式',
    dataIndex: 'server1mode',
    valueType: 'select',
    fieldProps: {
      placeholder: '请选择数据服务器1工作模式',
      options: format(serverWorkModeOptions.value),
    },
  },
  {
    title: '数据服务器1密码',
    dataIndex: 'server1psw',
    valueType: 'input',
  },
  {
    title: '数据服务器2IP',
    dataIndex: 'serverip2',
    valueType: 'input',
    formItemProps: {
      rules: [
        {
          required: true,
          validator: ipValid,
          trigger: 'blur',
        },
      ],
    },
  },
  {
    title: '数据服务器2端口号',
    dataIndex: 'serverport2',
    valueType: 'input',
    formItemProps: {
      rules: [
        {
          required: true,
          validator: portValid,
          trigger: 'blur',
        },
      ],
    },
  },
  {
    title: '数据服务器2工作模式',
    dataIndex: 'server2mode',
    valueType: 'select',
    fieldProps: {
      placeholder: '请选择数据服务器2工作模式',
      options: format(serverWorkModeOptions.value) as any,
    },
  },
  {
    title: '数据服务器2密码',
    dataIndex: 'server2psw',
    valueType: 'input',
  },
  {
    title: '备注：',
    dataIndex: 'remark',
    valueType: 'input',
    colProps: { span: 24 },
    formItemProps: {
      labelCol: {
        span: 0,
      },
    },
    render() {
      return <div></div>;
    },
  },
  {
    title: '',
    dataIndex: 'remark',
    valueType: 'input',
    colProps: { span: 24 },
    formItemProps: {
      labelCol: {
        span: 6,
      },
      wrapperCol: {
        span: 18,
      },
    },
    formItemRender() {
      return (
        <div class='pl-8'>
          <div>
            1、设备接入平台时，会根据设备的台网+台站作为设备在平台的唯一标识。用户修改台网或台站后，平台会将该设备作为新的设备接入。
          </div>
          <div>2、服务器地址修改以后会影响设备的接入状态。</div>
          <div>3、管理服务地址修改以后平台参数下发功能会失效。</div>
          <div>
            {' '}
            4、参数下发后，需要对设备进行重启，设备重新上线后会更新新的参数信息。设备状态的变更可能需要在设备重新上线后2分钟左右进行变更。若长时间无法变更，请再次重启设备。若仍然无法解决，请排查其他问题。
          </div>
        </div>
      );
    },
  },
]);
</script>

<style lang="scss" scoped></style>
